package com.SH.controller;

import com.SH.pojo.User;
import com.SH.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class UserController {

    @Autowired
    private UserService userService;


    @GetMapping("/user")
    public String getUsers(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "5") Integer pageSize, Model model){
        PageHelper.startPage(pageNum,pageSize);
        List<User> users = userService.getUsers();
        PageInfo pageInfo = new PageInfo(users);
        model.addAttribute("pageInfo",pageInfo);
        return "backstage/user";
    }


    @GetMapping("/user/{id}")
    public String getUser(@PathVariable("id") Integer id, Model model){
        User user = userService.getUserById(id);
        List<String> roles = userService.getRoles();
        model.addAttribute("user",user);
        model.addAttribute("roles",roles);
        return "backstage/userDetail";
    }

    @GetMapping("/saveUser")
    public String saveUser(User user){
        userService.updateUser(user);
        return "redirect:/user";
    }

    @GetMapping("/deleteUser/{id}")
    public String deleteUser(@PathVariable("id") Integer id){
        userService.deleteUser(id);
        return "redirect:/user";
    }
}
